<?php


namespace app\controllers;


use app\components\AppController;
use app\helpers\EmailHelper;
use app\models\User;
use app\models\UserPlatform;
use Yii;
use yii\authclient\OAuth2;
use yii\db\Exception;
use yii\validators\EmailValidator;
use yii\web\Response;

class AuthController extends AppController {

    public $layout = 'auth';
//    public $enableCsrfValidation = FALSE;

    public function beforeAction($action) {
        if (!parent::beforeAction($action)) {
            return FALSE;
        }
        if ($action->id !== 'logout' && !Yii::$app->user->getIsGuest()) {
            $this->goBack();
            return FALSE;
        }
        return TRUE;
    }

    public function actionRegister() {
        $model = new User();
        $model->setScenario('register');
        if ($model->load($this->post())) {
            return $model->register();
        }
        $this->view->title = Yii::t('app', 'Sign up');
        return !$this->isAjax() ? $this->render(compact('model')) : $this->renderPartial('/register', compact('model'));
    }

    public function actionLogin() {
        $model = new User();
        $model->setScenario('login');
        if ($model->load($this->post())) {
            return $model->login();
        }
        $this->view->title = Yii::t('app', 'Sign in');
        return !$this->isAjax() ? $this->render(compact('model')) : $this->renderPartial('/login', compact('model'));
    }

    public function actionForgotPassword() {

    }

    public function actionSendEmailCode() {
        $email = $this->getParam('value');
        $v = new EmailValidator();
        if (!$v->validate($email, $error)) {
            return $this->error($error);
        }
        return EmailHelper::sendCode($email);
    }

    public function actions() {
        $actions = parent::actions();
        $actions['index'] = [
            'class' => 'yii\authclient\AuthAction',
            'successCallback' => [$this, 'successCallback'],
        ];
        return $actions;
    }

    public function actionQq() {
        print_r($_REQUEST);
        return '';
    }

    public function actionWeibo() {

    }

    public function actionWechat() {
    }

    public function actionLogout() {
        Yii::$app->user->logout();
        return $this->refresh();
    }

    /**
     * @param OAuth2 $client
     * @return array|bool|Response
     * @throws Exception
     */
    public function successCallback(OAuth2 $client) {
        $userInfo = $client->getUserAttributes();
        $id = $client->getId();

        $userPlatform = new UserPlatform();
        $userPlatform->savePlatform($userInfo, $id);

        return $this->redirect(['user/identity']);
    }
}